package com.gin.pixiv.main

import com.gin.pixiv.api.*
import com.gin.pixiv.enums.Language
import com.gin.pixiv.interceptor.CookieInterceptor
import com.gin.pixiv.interceptor.LanguageInterceptor
import com.gin.pixiv.interceptor.TokenInterceptor
import com.gin.retrofit.utils.JacksonUtils
import com.gin.retrofit.utils.OkhttpUtils
import com.gin.retrofit.utils.RetrofitUtils
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.util.regex.Pattern

/**
 * @author bx002
 * @since 2024/2/18 11:16
 */
class Pixiv(private val retrofit: Retrofit) {
    companion object {
        const val DEFAULT_HOST = "https://www.pixiv.net/"
        private val TOKEN_PATTERN: Pattern = Pattern.compile("pixiv.context.token = \"(.+?)\";")

        /**
         * 创建OkHttpClient实例
         */
        @JvmStatic
        fun obtainOkHttpClient(phpSessionId: String, token: String?, language: Language = Language.zh): OkHttpClient {
            return OkhttpUtils.obtainOkHttpClient().newBuilder()
                .addInterceptor(LanguageInterceptor(language))
                .addInterceptor(CookieInterceptor(phpSessionId))
                .addInterceptor(TokenInterceptor(token))
                .build()
        }

        /**
         * 创建Retrofit实例
         */
        @JvmStatic
        fun obtainRetrofit(client: OkHttpClient, baseUrl: String = DEFAULT_HOST): Retrofit {
            return RetrofitUtils.obtainRetrofit(client, baseUrl, JacksonUtils.Companion.MAPPER)

        }
    }

    /**
     * 获取Token
     */
    fun fetchToken(): String {
        val response = settingApi().getSettingPage().execute()
        val body = response.body() ?: throw RuntimeException("response is null")
        val matcher = TOKEN_PATTERN.matcher(body.string())
        if (matcher.find()) {
            return matcher.group(1)
        } else {
            throw RuntimeException("token not found")
        }
    }


    /**
     * 插画相关API
     */
    fun illustrationApi(): IllustrationApi = retrofit.create(IllustrationApi::class.java)
    fun novelApi(): NovelApi = retrofit.create(NovelApi::class.java)
    fun bookmarkManageApi(): BookmarkManageApi = retrofit.create(BookmarkManageApi::class.java)
    fun settingApi(): SettingApi = retrofit.create(SettingApi::class.java)
    fun illustCommentApi(): IllustCommentApi = retrofit.create(IllustCommentApi::class.java)
    fun novelCommentApi(): NovelCommentApi = retrofit.create(NovelCommentApi::class.java)
    fun novelSeriesApi(): NovelSeriesApi = retrofit.create(NovelSeriesApi::class.java)
    fun rankingApi(): RankingApi = retrofit.create(RankingApi::class.java)
    fun tagApi(): TagApi = retrofit.create(TagApi::class.java)
    fun userApi(): UserApi = retrofit.create(UserApi::class.java)
    fun userWorkApi(): UserWorkApi = retrofit.create(UserWorkApi::class.java)
    fun bookmarkQueryApi(): BookmarkQueryApi = retrofit.create(BookmarkQueryApi::class.java)
    fun commissionApi(): CommissionApi = retrofit.create(CommissionApi::class.java)
}